package controllers

import (
	"GoIM/models"
	"GoIM/tools"
	"github.com/astaxie/beego"
)

type UserController struct {
	beego.Controller
}

func (this *UserController) Login() {
	Username := this.GetString("username")
	Password := this.GetString("password")
	if Username == "" || Password == "" {
		this.TplName = "login.html"
	} else {
		user := &models.User{Username: Username, Password: Password}
		err := models.Login(user)
		var data *ResultData
		if err == nil {
			this.SetSession("user", Username)
			data = &ResultData{Error: 0}
		} else {
			data = &ResultData{Error: 1}
		}
		this.Data["json"] = data
		this.ServeJSON()
	}
}

func (this *UserController) Register() {
	username := this.GetString("username")
	password := this.GetString("password")
	email := this.GetString("email")
	if username == "" {
		this.TplName = "register.html"
	} else {
		var data *ResultData
		user := &models.User{Username: username, Password: password, Email: email, Avatar: GetGravatar(email)}
		if err := models.Register(user); err != nil {
			data = &ResultData{Error: 1}
		} else {
			data = &ResultData{Error: 0}
		}
		this.Data["json"] = data
		this.ServeJSON()
	}
}

// 获得gravatar头像
func GetGravatar(email string) string {
	result := tools.StringToMd5(email, 0)
	return "http://cn.gravatar.com/avatar/" + result + "&d=identicon"
}
